import constantRoutesList from "@/router/modules/routes";
import { usePermissionStoreHook } from "@/store/modules/permission";
import {
  ascending,
  getHistoryMode,
  // formatTwoStageRoutes,
  filterNoPermissionRoute,
  formatFlatteningRoutes
} from "./utils";
import {
  type Router,
  type RouteComponent,
  type RouteRecordRaw,
  createRouter
} from "vue-router";
import { setupRouterHooks } from "./setup";

export const constantRoutes: Array<RouteRecordRaw> = formatFlatteningRoutes(
  ascending(constantRoutesList.flat(Infinity))
);

export const constantMenus: Array<RouteComponent> = ascending(
  constantRoutesList.flat(Infinity)
);

/** 创建路由实例 */
export const router: Router = createRouter({
  history: getHistoryMode(import.meta.env.VITE_ROUTER_HISTORY),
  routes: constantRoutes as RouteRecordRaw[],
  strict: true,
  scrollBehavior(to, from, savedPosition) {
    return new Promise(resolve => {
      if (savedPosition) {
        return savedPosition;
      } else {
        if (from.meta.saveSrollTop) {
          const top: number =
            document.documentElement.scrollTop || document.body.scrollTop;
          resolve({ left: 0, top });
        }
      }
    });
  }
});

export function addRouter(routes: RouteRecordRaw[]) {
  routes.forEach((route: RouteRecordRaw) => {
    if (!router.hasRoute(route.name)) {
      router.addRoute(route);
    }
    if (route.children) {
      addRouter(route.children);
    }
  });
}

export function fatteningRoutes(routes: RouteRecordRaw[]): RouteRecordRaw[] {
  return routes.flatMap((route: RouteRecordRaw) => {
    return route.children ? fatteningRoutes(route.children) : route;
  });
}

export function resetRouter(routes: RouteRecordRaw[]) {
  routes = filterNoPermissionRoute(
    formatFlatteningRoutes(ascending(routes.flat(Infinity)))
  );
  router.getRoutes().forEach((route: RouteRecordRaw) => {
    if (router.hasRoute(route.name)) {
      router.removeRoute(route.name);
    }
  });
  addRouter(routes);
  // addPathMatch();
}

/** 重置路由 */
export function clearRouter() {
  router.getRoutes().forEach(route => {
    const { name, meta } = route;
    if (name && router.hasRoute(name) && meta?.backstage) {
      router.removeRoute(name);
    }
  });
  router.options.routes = constantRoutes;
  usePermissionStoreHook().clearAllCachePage();
}

export function setupRouter(app: any) {
  setupRouterHooks(router);
  app.use(router);
  return router;
}

export default router;
